package cm.tl.pms.util;

import lombok.SneakyThrows;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

/**
 * AES对称加密算法的封装工具类
 *
 * @author w7h1te_ywq
 * @version 1.0.0
 * @date 2024-06-05 14:06
 */
public class AesEncryptionUtil {

    public static final String KEY = "9!#95hsup*&$1zq7";

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    // 加密
    @SneakyThrows
    public static String encrypt(String plainText, String key) {
        Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }


    // 解密
    @SneakyThrows
    public static String decrypt(String encryptedText, String key) {
        Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }


    public static void main(String[] args) {
        //密钥的长度是16字节、24字节或32字节
//        String key = UUID.randomUUID().toString().replace("-", "");
//        System.out.println(key);
//        String key = "0123456789abcdef"; // 16字节的密钥
        String plainText = "3";
//        String plainText = "1";

        // 加密
        String encryptedText = AesEncryptionUtil.encrypt(plainText, KEY);
        System.out.println("加密后的数据: " + encryptedText);

        // 解密
        String decryptedText = AesEncryptionUtil.decrypt(encryptedText, KEY);
        System.out.println("解密后的数据: " + decryptedText);
    }

}
